namespace WebRtcProject.Services.Logging
{
    public class LogResourceManagerHostedService : BackgroundService
    {
        private readonly ILogResourceManager _logResourceManager;
        private readonly ILogger<LogResourceManagerHostedService> _logger;

        public LogResourceManagerHostedService(
            ILogResourceManager logResourceManager,
            ILogger<LogResourceManagerHostedService> logger)
        {
            _logResourceManager = logResourceManager;
            _logger = logger;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Log Resource Manager Hosted Service is starting");
            
            try
            {
                await _logResourceManager.InitializeAsync();
                _logger.LogInformation("Log Resource Manager initialized successfully");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to initialize Log Resource Manager");
                throw;
            }

            await base.StartAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Log Resource Manager Hosted Service is running");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    // 定期检查资源状态
                    await Task.Delay(TimeSpan.FromMinutes(30), stoppingToken);
                    
                    var status = await _logResourceManager.GetResourceStatusAsync();
                    
                    if (!status.IsMemoryWithinLimit)
                    {
                        _logger.LogWarning("Memory usage is above limit: {CurrentMB}MB / {MaxMB}MB", 
                            status.CurrentMemoryUsageMB, status.MaxMemoryUsageMB);
                    }
                    
                    if (!status.IsLogSizeWithinLimit)
                    {
                        _logger.LogWarning("Log size is above limit: {CurrentMB}MB / {MaxMB}MB", 
                            status.TotalLogSizeMB, status.MaxLogSizeMB);
                        
                        // 触发清理
                        await _logResourceManager.CleanupOldLogsAsync();
                    }
                }
                catch (OperationCanceledException)
                {
                    // 正常取消操作
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error during log resource monitoring");
                }
            }
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Log Resource Manager Hosted Service is stopping");
            
            try
            {
                _logResourceManager.StopBackgroundCleanup();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error stopping log resource manager");
            }

            await base.StopAsync(cancellationToken);
        }
    }
} 